# -*- coding:utf-8 -*-
"""
链一财经
https://www.lianyi.com/

"""
import requests
from cs import day
import time
from WriteData import writedata
from Tk import genearteMD5


def get_html_text(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    try:
        r = requests.get(url, timeout=30, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_dates(url):
    text = get_html_text(url)
    if not text:
        return None
    text = eval(text)
    data = text['data']['data']
    dates = [date['publish_time'] for date in data]
    return dates


def count_process_xw():
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    b = 1
    a = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    while b < 200:
        url = 'https://www.lianyi.com/api/news/search?keyword=&up_time={}'
        url = url.format(a)
        print('---- 链一财经首页获取第{}页----'.format(b))
        b += 1
        dates = get_dates(url)
        if not dates:
            continue
        a = dates[-1]
        for date in dates:
            s = day(date[:10])
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        if d4 > 0:
            break
    return (d1, d2, d3)


def main():
    u = '链一财经'
    t1 = count_process_xw()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0], "yesterday": t1[1], "frontday": t1[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
